<template>
  <form-panel :form="data.form" :submitUrl="data.submitUrl" ref="formPanelRef" @update="update"
              :queryUrl="data.queryUrl" :id="data.id" :formTitle="data.formTitle">
    <el-form-item
        label="登录账号"
        :rules="[
          { required: true, message: '请输入用户名字', trigger: 'blur' }
        ]"
        prop="username"
    >
      <v-input v-model="data.form.username" placeholder="请输入用户名字" :width="data.width"
      />
    </el-form-item>
    <el-form-item
        label="姓名"
        :rules="[{ required: true, message: '请输入昵称', trigger: 'blur' }]"
        prop="nickname"
    >
      <v-input v-model="data.form.nickname" placeholder="请输入昵称" :width="data.width"/>
    </el-form-item>
    <el-form-item
        label="密码"
        :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        prop="password"
        v-if="data.mode === 'create'"
    >
      <v-input v-model="data.form.password" type="password" placeholder="请输入密码" :width="data.width"/>
    </el-form-item>
  </form-panel>
</template>
<script lang="ts" setup>
import {reactive, onMounted, ref} from 'vue'
import {useRoute} from 'vue-router'

const $route = useRoute();
const data = reactive({
  form: {
    username: '',
    password: '',
    nickname: '',
  },
  id: '',
  submitUrl: '/api/user/register',
  userId: undefined,
  mode: '',
  queryUrl: '/api/user/getDetail',
  width: 300,
  formTitle: '新增用户'
})
const formPanelRef = ref()

onMounted(() => {
  const {id} = $route.query
  if (id === undefined) {
    data.mode = 'create'
    data.submitUrl = '/api/user/register'
    data.formTitle = '新增用户'
  } else {
    data.mode = 'update'
    data.id = id as string
    data.submitUrl = '/api/user/update'
    data.formTitle = '编辑用户'
    formPanelRef.value.getData({
      id
    })
  }
})

const update = (params) => {
  Object.keys(params).forEach(key => {
    data.form[key] = params[key]
  })
}
</script>
<style scoped lang="scss"></style>
